package com.jm.common.exception;

import com.jm.common.util.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 异常处理器 根据根据注解拦截
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class ExceptionHandling {
    /**
     * Sql主键重复异常
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> sqlExceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        log.error(message);
        if (message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String noticeMessage = split[2]+" 已存在请进行更换";
            return R.error(noticeMessage);
        }
        return R.error("Sql语句不符合规范,请检查程序或者Sql语句");
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public R<String> serviceExceptionHandler(ServiceException ex){
        String message = ex.getMessage();
        log.error(message);
        return R.error(message);
    }

    /**
     * FileNotFoundException 文件查找不到异常
     */
    @ExceptionHandler(FileNotFoundException.class)
    public R<String> fileException(FileNotFoundException ex){
        String message = ex.getMessage();
        log.error(message);
        message="此次删除找不到要删除的本地菜品图片文件";
        return R.error(message);
    }

}
